import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from db.db_util import DBUtil
from entities.food import Food

class FoodDao:
    def list_by_business(self, business_id):
        conn = None
        cursor = None
        try:
            conn = DBUtil.get_connection()
            cursor = conn.cursor()
            sql = "SELECT * FROM food WHERE businessId = %s"
            cursor.execute(sql, (business_id,))
            results = cursor.fetchall()
            foods = []
            for result in results:
                foods.append(Food(
                    food_id=result['foodId'],
                    food_name=result['foodName'],
                    food_explain=result['foodExplain'],
                    food_price=float(result['foodPrice']),
                    business_id=result['businessId']
                ))
            return foods
        finally:
            DBUtil.close(conn, cursor)

    def add(self, food):
        conn = None
        cursor = None
        try:
            conn = DBUtil.get_connection()
            cursor = conn.cursor()
            sql = """INSERT INTO food 
                     (foodName, foodExplain, foodPrice, businessId) 
                     VALUES (%s, %s, %s, %s)"""
            cursor.execute(sql, (
                food.food_name,
                food.food_explain,
                food.food_price,
                food.business_id
            ))
            conn.commit()
            return cursor.lastrowid
        except Exception as e:
            conn.rollback()
            raise e
        finally:
            DBUtil.close(conn, cursor)

    def update(self, food):
        conn = None
        cursor = None
        try:
            conn = DBUtil.get_connection()
            cursor = conn.cursor()
            sql = """UPDATE food SET 
                     foodName=%s, foodExplain=%s, foodPrice=%s 
                     WHERE foodId=%s"""
            cursor.execute(sql, (
                food.food_name,
                food.food_explain,
                food.food_price,
                food.food_id
            ))
            conn.commit()
            return cursor.rowcount
        except Exception as e:
            conn.rollback()
            raise e
        finally:
            DBUtil.close(conn, cursor)

    def delete(self, food_id):
        conn = None
        cursor = None
        try:
            conn = DBUtil.get_connection()
            cursor = conn.cursor()
            sql = "DELETE FROM food WHERE foodId = %s"
            cursor.execute(sql, (food_id,))
            conn.commit()
            return cursor.rowcount
        except Exception as e:
            conn.rollback()
            raise e
        finally:
            DBUtil.close(conn, cursor)